<template>
    <div>
        <div class="flex">
            <a-button @click="handleUpDate">
                <Iconfont class="icon net-card-icon" type="icon-rollback16f1"></Iconfont>
            </a-button>
            <a-input v-model="input" :placeholder="$t('Enter')" class="ml-10" style="width: 180px;" />
            <a-button type='primary' class="ml-8" @click="handleSearch">
                <Iconfont class="icon button-icon-style" type="icon-search16f"></Iconfont>
                {{ $t('查询') }}
            </a-button>
        </div>

        <a-table class="bigstyle mt-16" :columns='columns' :loading="loading" :dataSource='dataList'
            :locale="defaultSetting" :pagination='pagination' size='small' :scroll="{ x: 1340 }">
            <!-- 本地集群 -->
            <template slot="type" slot-scope="text, record">
                <a-tooltip placement='top'>
                    <template slot='title'>
                        <span>{{ record.cluster_name }}</span>
                    </template>
                    <span>{{ record.cluster_name }}</span>
                </a-tooltip>
            </template>
            <!-- 本地块设备 -->
            <template slot="name" slot-scope="text, record">
                <div v-if="record.pool_name && record.image_name">
                    <span>{{ record.pool_name }}\{{ record.image_name }}</span>
                    <div>
                        <a-tag :class="getread.get(record.readwrite)">{{ readwriteMap.get(record.readwrite) }}</a-tag>
                        <a-tag :class="getprimary.get(record.primary)">{{ primaryMap.get(record.primary) }}</a-tag>
                    </div>
                </div>
                <div v-else>-</div>
            </template>
            <!-- 保护类型 -->
            <template slot="type" slot-scope="text, record">
                <span>{{ protectTypeMap.get(record.mode) }}</span>
            </template>
            <!-- 状态 -->
            <template slot="status" slot-scope="text, record">
                <a-tooltip placement='top' :getPopupContainer="getPopupContainer">
                    <template slot='title' v-if="record.description">
                        <span>{{ record.description }}</span>
                    </template>

                    <span>
                        <span v-if="record.health == 'ok' && record.state != 'stop' && record.state != 'snycing'"
                            class="green-circle"></span>
                        <span v-else-if="record.health == 'issue'" class="red-circle"></span>
                        <span v-else-if="record.health == 'snycing' || record.state == 'snycing'"
                            class="blue-circle"></span>
                        <span v-else-if="record.health == 'stop' || record.state == 'stop'" class="grey-circle"></span>

                        <span v-if="record.state == 'stop'">已暂停-</span>
                        <span v-else-if="record.state == 'snycing'">同步中-</span>
                        <span v-else> {{ healthStatusMap.get(record.health) }} - {{ record.state }}</span>
                    </span>
                </a-tooltip>
            </template>
            <!-- 集群连接状态 -->
            <template slot="connect_health" slot-scope="text, record">
                <span v-if="record.connect_health == false" class="red-circle"></span>
                <span v-else-if="record.connect_health == true" class="green-circle"></span>
                <span>{{ statusMap.get(record.connect_health) }}</span>
            </template>
            <!-- 策略计划 -->
            <template slot="plan" slot-scope='text, record'>
                <div v-if="record.mode == 0">-</div>
                <div v-else>
                    <a-tag v-if="record.raw_cycle_type" :class="cycleTypeColor.get(record.raw_cycle_type)">{{
                        cycleType.get(record.raw_cycle_type) }}</a-tag>
                    <span v-if="Array.isArray(record.raw_cycles)">{{ record.raw_cycles.join(',') }}</span>
                    <!-- 时间段 -->
                    <span v-if="record.raw_time_type == '1'">
                        <span class="ml-6" v-if="record.raw_start_time && record.raw_end_time">{{
                            record.raw_start_time }} - {{ record.raw_end_time }}</span>
                        <div>
                            <span v-if="record.raw_every_few_type == '1'">{{ $t('每') }}{{ record.raw_every_few
                                }}{{ $t('分钟') }}{{ $t('执行一次') }}</span>
                            <span v-if="record.raw_every_few_type == '2'">{{ $t('每') }}{{ record.raw_every_few
                                }}{{ $t('小时') }}{{ $t('执行一次') }}</span>
                        </div>
                    </span>
                    <!-- 时间点 -->
                    <div v-if="record.raw_time_type == '2'">{{ record.raw_time }}{{ $t('执行一次') }}</div>
                </div>
            </template>
            <template slot="operate" slot-scope='text, record'>
                <div class="flex" v-userAuth="'H1-2'">
                    <div>
                        <a v-if="record.mode == 1 && record.primary == 0" class="$color-theme-main"
                            @click="handleSync(record.pool_name, record.image_name)">{{ $t('同步') }}</a>
                        <span v-else disabled>{{ $t('同步') }}</span>
                    </div>
                    <div class="ml-6">
                        <a v-if="record.mode == 1 && record.primary == 0 && record.state != 'stop' && record.is_create == true"
                        class="$color-theme-main" @click="handleStop(record.pool_name, record.image_name)">{{ $t('暂停')
                            }}</a>
                        <span v-else disabled>{{ $t('暂停') }}</span>
                    </div>
                    <div class="ml-6">
                        <a v-if="record.mode == 1 && record.primary == 0 && record.state == 'stop' && record.is_create == true"
                             class="$color-theme-main" @click="handleRecover(record.image_name, record.pool_name)">{{
                                $t('恢复') }}</a>
                        <span v-else disabled>{{ $t('恢复') }}</span>
                    </div>
                    <div class="ml-6">
                        <a v-if="record.primary == 1" class="$color-theme-main"
                            @click="handleChange(record.pool_name, record.image_name, record.state, record.mode, record.connect_health)">{{
                                $t('故障切换') }}</a>
                        <span v-else disabled>{{ $t('故障切换') }}</span>
                    </div>

                </div>
            </template>

        </a-table>
        <!-- <span style="margin-left: 8px">
            <template v-if="hasSelected">
                {{ `Selected ${selectedRowKeys.length} items` }}
            </template>
        </span> -->

        <failover ref="changeRef" @get-list="getList" :picContent="picContent" :logContent="logContent"
            :tipContent="tipContent" />
    </div>
</template>

<script>
import EmptyData from '@/components/common/EmptyData'
import failover from './failover';

export default {
    name: 'blockStorage',
    components: { EmptyData, failover },
    data() {
        return {
            loading: false,
            toRecover: false,
            dataList: [],
            strategyOption: [],
            copyList: [],
            defaultSetting: { emptyText: <EmptyData /> },
            pagination: {
                defaultPageSize: 10,
                showTotal: total => `${this.$t('A-total-of')} ${total} ${this.$t('Data')}`,
                showSizeChanger: true,
                pageSizeOptions: ['10', '20', '30', '40', '50', '100'],
                onShowSizeChange: (current, pageSize) => this.pageSize = pageSize,
                buildOptionText: (props) => `${props.value} / ${this.$t('page')}`
            },
            columns: [
                { title: this.$t('本地集群'), dataIndex: 'cluster_name', key: 'cluster_name', width: 160, fixed: 'left', ellipsis: true, scopedSlots: { customRender: 'cluster_name' } },
                { title: this.$t('本地块设备'), dataIndex: 'name', key: 'name', width: 200, fixed: 'left', scopedSlots: { customRender: 'name' } },
                { title: this.$t('远端集群'), dataIndex: 'remote_cluster_name', key: 'remote_cluster_name', width: 160 },
                { title: this.$t('保护类型'), dataIndex: 'type', key: 'type', width: 120, scopedSlots: { customRender: 'type' } },
                { title: this.$t('状态'), dataIndex: 'status', key: 'status', width: 200, scopedSlots: { customRender: 'status' } },
                { title: this.$t('集群连接状态'), dataIndex: 'connect_health', key: 'connect_health', width: 140, scopedSlots: { customRender: 'connect_health' } },
                { title: this.$t('保护策略详情'), dataIndex: 'plan', key: 'plan', width: 280, scopedSlots: { customRender: 'plan' } },
                { title: this.$t('Operate'), key: "operate", scopedSlots: { customRender: 'operate' }, width: 200, fixed: 'right' }
            ],
            selectedRowKeys: [], // Check here to configure the default column
            input: '',
            cycleType: new Map([
                [1, "每日"],
                [2, "每周"],
                [3, "每月"],
            ]),
            cycleTypeColor: new Map([
                [1, "blueColor"],
                [2, "greenColor"],
                [3, "purpleColor"],
            ]),
            healthStatusMap: new Map([
                ["ok", "健康"],
                ["issue", "异常"],
                ["syncing", "同步中"],
                ["stop", "已暂停"]

            ]),
            protectTypeMap: new Map([
                [0, "日志"],
                [1, "快照"]
            ]),
            primaryMap: new Map([
                [0, "主"],
                [1, "从"],
                [2, "切换中"]
            ]),
            readwriteMap: new Map([
                [true, "读写"],
                [false, "只读"]
            ]),
            statusMap: new Map([
                [true, "正常"],
                [false, "异常"]
            ]),
            getread: new Map([
                [true, "blueColor"],
                [false, "purpleColor"]
            ]),
            getprimary: new Map([
                [0, "blueColor"],
                [1, "purpleColor"],
                [2, "greyColor"]
            ]),
            picContent: false,
            logContent: false,
            tipContent: true
        }
    },
    // computed: {
    //     hasSelected() {
    //         return this.selectedRowKeys.length > 0;
    //     },
    // },
    mounted() {
        this.getList()
        this.timer = setInterval(() => this.getList(), 300000)
    },
    beforeDestroy() {
        clearInterval(this.timer)
        this.timer = undefined
    },
    methods: {
        getPopupContainer(triggerNode) {
            return triggerNode.parentNode;
        },
        // start() {
        //     this.loading = true;
        //     // ajax request after empty completing
        //     setTimeout(() => {
        //         this.loading = false;
        //         this.selectedRowKeys = [];
        //     }, 1000);
        // },
        // onSelectChange(selectedRowKeys) {
        //     console.log('selectedRowKeys changed: ', selectedRowKeys);
        //     this.selectedRowKeys = selectedRowKeys;
        // },
        async getList() {
            this.loading = true
            // this.dataList.push(
            //     { cluster_name: "111", remote_cluster_name: "ssxss", mode: 1, connect_health: true, health: "ok", state: "Primary", primary: 0, readwrite: true, pool_name: "ssssdssss", image_name: "fdsfsvssvs", description: "svdvfbfbf", is_create: true,},
            //     { cluster_name: "pxpp", remote_cluster_name: "sssss", mode: 0, connect_health: true, health: "ok", state: "Unknown", primary: 0, readwrite: true, pool_name: "ssssdssss", image_name: "fdsfsvssvs", description: "", is_create: true, },
            //     // { cluster_name: "kkskk", remote_cluster_name: "ssgss", mode: 1, connect_health: false, health: "ok", state: "snycing", primary: 0, readwrite: true, pool_name: "ssssdssss", image_name: "fdsfsvssvs", description: "dvfbfgnsdsfs", is_create: false },
            //     // { cluster_name: "pppdp", remote_cluster_name: "sssls", mode: 1, connect_health: false, health: "ok", state: "stop", primary: 0, readwrite: true, pool_name: "ssssdssss", image_name: "fdsfsvssvs", description: "dvfbfgnsdsfs" },
            //     // { cluster_name: "hhsh", remote_cluster_name: "ssbss", mode: 0, connect_health: true, health: "ok", state: "Starting", primary: 2, readwrite: false, pool_name: "ssssdssss", image_name: "fdsfsvssvs", description: "dvfbfgnsdsfs" },
            //     { cluster_name: "nnnn", remote_cluster_name: "sssms", mode: 0, connect_health: true, health: "ok", state: "Error", primary: 1, readwrite: false, pool_name: "ssssdssss", image_name: "fdsfsvssvs", description: "" },
            // )
            const { data } = await this.$api.data.getBlockStorageListApi()
            this.dataList = data.mirror_images_info
            this.copyList = data.mirror_images_info
            this.loading = false
        },
        handleSearch() {
            this.loading = true
            const list = []; // 用于存放搜索出来数据的新数组
            if (this.input) {
                this.copyList.filter((item) => {
                    if (item.pool_name.indexOf(this.input) !== -1) {
                        list.push(item);
                    } else if (item.image_name.indexOf(this.input) !== -1) {
                        list.push(item);
                    }
                });
                this.dataList = list;
            } else {
                this.dataList = this.copyList
            }
            this.loading = false
        },
        async handleUpDate() {
            await this.getList()
        },
        async handleSync(pool_name, image_name) {
            this.loading = true
            let _this = this
            this.$confirm({
                content: this.$t('同步过程将对两端业务性能产生一定的影响，建议在业务不繁忙时进行。确定立即开始同步吗？'),
                cancelText: this.$t('Cancel'),
                okText: this.$t('同步'),
                async onOk() {
                    const { data } = await _this.$api.data.syncBlockStorageApi({ pool_name, image_name })
                    _this.model(data.id) //返回模板
                    _this.notice(data.id, data.params, data.flag) //通知列表显示
                    if (data.flag == 0) _this.getList()
                },
                onCancel() {
                }
            })
            this.loading = false
        },

        async handleStop(pool_name, image_name) {
            this.loading = true
            let _this = this
            this.$confirm({
                content: h => <div style='margin-left: 40px'>
                    {_this.$t('暂停后将保留当前复制关系、目标卷及快照，但暂停后的新数据不会被同步。状态为同步中的复制关系将在完成本次保护任务之后暂停。确定暂停快照复制吗？')}
                </div>,
                cancelText: this.$t('Cancel'),
                okText: this.$t('暂停'),
                icon: 'question-circle',
                async onOk() {
                    const { data } = await _this.$api.data.stopBlockStorageApi({ pool_name, image_name })
                    _this.model(data.id) //返回模板
                    _this.notice(data.id, data.params, data.flag) //通知列表显示
                    if (data.flag == 0) _this.getList()
                },
                onCancel() {
                }
            })
            this.loading = false
        },

        async handleRecover(image_name, pool_name) {
            this.loading = true
            let _this = this
            this.$confirm({
                // title: this.$t('Delete') + this.$t('块存储卷快照复制'),
                content: this.$t('恢复后本地数据将按照保护策略同步至远端集群。确定恢复快照复制吗？'),
                cancelText: this.$t('Cancel'),
                okText: this.$t('恢复'),
                // icon: 'close-circle',
                async onOk() {
                    const { data } = await _this.$api.data.recoverBlockStorageApi({ image_name, pool_name })
                    _this.model(data.id) //返回模板
                    _this.notice(data.id, data.params, data.flag) //通知列表显示
                    if (data.flag == '0') _this.getList()
                },
                onCancel() {
                }
            })
            this.loading = false
        },

        async handleChange(pool_name, image_name, state, mode, connect_health,) {
            if (mode == 1 && connect_health == true && (state == 'Primary' || state == 'Replaying' || state == 'stop' || state == 'Starting')) {
                this.tipContent = false
                this.picContent = true
                this.$refs.changeRef.connect_health = true
            } else if (mode == 1 && connect_health == true && (state == 'Error' || state == 'Unknown')) {
                this.tipContent = false
                this.picContent = false
                this.$refs.changeRef.connect_health = true
            } else if (mode == 1 && connect_health == false && (state == 'Primary' || state == 'Replaying' || state == 'stop' || state == 'Starting')) {
                this.tipContent = false
                this.picContent = true
                this.$refs.changeRef.connect_health = false
            } else if (mode == 1 && connect_health == false && (state == 'Error' || state == 'Unknown')) {
                this.tipContent = false
                this.picContent = false
                this.$refs.changeRef.connect_health = false

            } else if (mode == 0 && (state == 'Primary' || state == 'Replaying' || state == 'stop' || state == 'Starting')) {
                this.tipContent = true
                this.logContent = true
            } else if (mode == 0 && (state == 'Error' || state == 'Unknown')) {
                this.tipContent = true
                this.logContent = false
            }

            this.$refs.changeRef.form.pool_name = pool_name
            this.$refs.changeRef.form.image_name = image_name
            this.$refs.changeRef.isShow = true
        },

    }
}
</script>

<style scoped>
::v-deep .ant-tooltip-inner {
    color: black;
    background-color: white;
}

::v-deep .ant-tooltip-arrow::before {
    background-color: white;
}

.blueColor {
    color: #006db8;
    background-color: rgb(0, 109, 184, 8%);
    text-align: center;
    border-radius: 4px;
    border: solid 1px #006db8;
}

.purpleColor {
    color: #6634b3;
    background-color: rgb(102, 52, 179, 8%);
    text-align: center;
    border-radius: 4px;
    border: solid 1px #6634b3;
}

.greyColor {
    color: #666666;
    background-color: rgb(102, 102, 102, 8%);
    text-align: center;
    border-radius: 4px;
    border: solid 1px #666666;
}

.greenColor {
    background-color: #ebf7f9;
    border-radius: 4px;
    border: solid 1px #059db3;
}
</style>